<template>
  <div class="task-list-container">
    <div class="task-list-container-toolbar">
      <el-button
        icon="el-icon-plus"
        circle
        title="编辑"
        @click="addTask"
      />
      <el-button
        icon="el-icon-refresh"
        circle
        title="刷新"
        @click="$fetch"
      />
    </div>
    <el-table
      v-loading="$fetchState.pending"
      :data="taskList"
      :height="height"
      style="width: 100%"
    >
      <template #empty>
        <el-button
          type="text"
          @click="addTask"
        >
          点击创建你的第一个任务
        </el-button>
      </template>
      <el-table-column
        prop="remindTime"
        label="提醒时间"
        width="180"
      >
        <template #default="{row}">
          <template v-if="row.remindTime">
            {{ row.remindTime | formatDate }}
          </template>
          <template v-else>
            未设置
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="content"
        label="内容"
        min-width="400"
      />
      <el-table-column
        prop="createdAt"
        label="创建时间"
        width="180"
      >
        <template #default="{row}">
          {{ row.createdAt | formatDate }}
        </template>
      </el-table-column>
      <el-table-column
        :fixed="fixedOperationCol"
        label="操作"
        width="160"
      >
        <template #default="{row}">
          <el-button
            class="el-icon-edit"
            circle
            title="编辑"
            @click="editTask(row)"
          />
          <el-popconfirm
            title="确定删除吗"
            @confirm="deleteTask(row)"
          >
            <template #reference>
              <el-button
                class="el-icon-delete"
                circle
                type="danger"
                title="删除"
              />
            </template>
          </el-popconfirm>
          <el-popconfirm
            title="确定完成吗"
            @confirm="completeTask(row)"
          >
            <template #reference>
              <el-button
                class="el-icon-finished"
                circle
                type="success"
                title="任务完成"
              />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="formTitle"
      :visible.sync="taskFormVisible"
    >
      <taskForm
        :task-id="selectedTaskId"
        @submitted="afterFormSubmitted"
      />
    </el-dialog>
  </div>
</template>

<script>
import * as dayjs from 'dayjs';
import taskApiBinder from '@/axios/task';
import { successMsg } from '@/utils/message';

export default {
  name: 'TaskListComp',
  filters: {
    formatDate(date) {
      // 格式化日期
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  props: {
    height: {
      type: Number,
      default: 700
    }
  },
  data() {
    return {
      taskList: [],
      selectedTaskId: '',
      pickerOptions: {},
      taskFormVisible: false
    };
  },
  async fetch() {
    await this.getTaskList();
  },
  computed: {
    formTitle() {
      return (this.selectedTaskId ? '编辑' : '新增') + '任务';
    },
    fixedOperationCol() {
      return this.taskList.length ? 'right' : false;
    }
  },
  created() {
    this.apis = taskApiBinder(this);
  },
  fetchOnServer: false,
  methods: {
    handleTaskRes({ id, content, remindTime, isCompleted, createdAt, updatedAt }) {
      return {
        id,
        content,
        remindTime: remindTime ? new Date(remindTime) : remindTime,
        isCompleted,
        createdAt: new Date(createdAt),
        updatedAt: new Date(updatedAt)
      };
    },
    async getTaskList() {
      const listRes = await this.apis.getList({ isCompleted: 0, sort: 'createdAt', order: 'DESC' });
      this.taskList = listRes.data.map(this.handleTaskRes);
    },
    addTask() {
      this.selectedTaskId = '';
      this.taskFormVisible = true;
    },
    editTask({ id }) {
      this.selectedTaskId = id;
      this.taskFormVisible = true;
    },
    async afterFormSubmitted(info) {
      this.taskFormVisible = false;
      const res = await this.apis.getById(info.id);
      const toInsertTask = this.handleTaskRes(res.data);
      if (info.type === 'created') {
        successMsg('添加成功');
        this.taskList.unshift(toInsertTask);
      } else if (info.type === 'updated') {
        successMsg('更新成功');
        const index = this.taskList.findIndex(task => task.id === toInsertTask.id);
        this.taskList.splice(index, 1, toInsertTask);
      }
    },
    async deleteTask({ id }) {
      const res = await this.apis.deleteById(id);
      if (res.success) {
        successMsg('任务已经删除');
        this.deleteTaskInList(id);
      }
    },
    async completeTask({ id }) {
      const res = await this.apis.updateById(id, { isCompleted: true });
      if (res.success) {
        successMsg('任务已经完成，可以在“已完成列表”查看');
        this.deleteTaskInList(id);
      }
    },
    deleteTaskInList(id) {
      const index = this.taskList.findIndex(task => task.id === id);
      this.taskList.splice(index, 1);
    }
  }
};
</script>

<style scoped lang="scss">
.task-list-container {
  &-toolbar {
    text-align: right;
  }
}
</style>
